<template>
  <div ref="chart" style="width: 100%; height: 100%"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted } from 'vue'

const chart = ref(null)
let myChart

onMounted(() => {
  myChart = echarts.init(chart.value)
  updateChart() // 初始化时更新图表数据，可以根据需要进行更改
  addEventListener('resize', resizeChart) // 监听浏览器窗口大小变化，更新图表大小
})

onUnmounted(() => {
  if (myChart) {
    myChart.dispose() // 销毁图表，释放资源
  }
  removeEventListener('resize', resizeChart) // 移除监听
})

// Props
const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  legend: {
    type: Array,
    default: null
  }
})

// Methods
const updateChart = () => {
  if (!myChart || !props.data) return

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: props.legend
      ? props.legend
      : {
          show: true,
          orient: 'vertical',
          left: '50%',
          top: 'center',
          itemWidth: 8,
          itemHeight: 8,
          icon: 'circle',
          textStyle: {
            fontSize: 12, // 字体大小
            color: '#999' // 字体颜色
          },
          formatter: function (name) {
            const total = props.data.reduce((sum, item) => sum + item.value, 0)
            const current = props.data.find((item) => item.name === name)
            const percent = (current?.value / total && ((current?.value / total) * 100).toFixed(2)) || 0
            return `${name}  ${percent}%`
          }
        },
    tooltip: {
      trigger: 'item', // 触发类型
      formatter: '{b}: {d}%' // 显示的格式
    },
    color: ['#6699ff', '#52cca3', '#a1e6ce', '#b3cdff', '#bfb3ff', '#7d8fb3'],
    series: [
      {
        name: 'Pie chart',
        type: 'pie',
        radius: '70%',
        center: ['25%', '50%'],
        data: props.data,
        // emphasis: {
        //   itemStyle: {
        //     shadowBlur: 10,
        //     shadowOffsetX: 0,
        //     shadowColor: 'rgba(0, 0, 0, 0.5)'
        //   }
        // },
        label: {
          show: false
        },
        itemStyle: {
          normal: {
            borderRadius: 2,
            borderColor: 'rgba(255, 255, 255, 1 )',
            borderWidth: 1
          }
        }
      }
    ]
  }

  myChart.setOption(option)
}

const resizeChart = () => {
  if (!myChart) return
  myChart.resize()
}
// Watcher
watchEffect(() => {
  updateChart()
})
defineExpose({
  resizeChart
})
</script>

<style scoped>
/* 根据需要添加样式 */
</style>
